/*
 * The MIT License (MIT)
 * 
 * Copyright (c) 2014 Dameng Database Inc.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.dm.demo.repository.jpa.dao;

import com.dm.demo.repository.dao.IdeaDao;
import com.dm.demo.repository.jpa.po.IdeaPo;
import com.dm.demo.repository.jpa.repository.IdeaRepository;
import com.dm.demo.repository.pojo.IdeaPojo;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * Title.
 * <p/>
 * Description.
 *
 * @author Bill Lv {@literal <billcc.lv@hotmail.com>}
 * @version 1.0
 * @since 2014-12-05
 */
@Repository
public class IdeaDaoImpl implements IdeaDao {
    @Autowired
    private IdeaRepository repository;

    @Autowired
    private Mapper mapper;

    @Override
    public List<IdeaPojo> findAll() {
        List<IdeaPo> poList = repository.findAll();
        List<IdeaPojo> pojoList = new ArrayList<>(poList.size());
        for (IdeaPo po : poList) {
            pojoList.add(mapper.map(po, IdeaPojo.class));
        }
        return pojoList;
    }

    @Override
    public IdeaPojo update(IdeaPojo ideaPojo) {
        IdeaPo po = repository.findOne(ideaPojo.getId());
        po.setDescription(ideaPojo.getDescription());
        po.setVotes(ideaPojo.getVotes());
        po.setTitle(ideaPojo.getTitle());
        repository.saveAndFlush(po);
        return mapper.map(po, IdeaPojo.class);
    }

    @Override
    public IdeaPojo create(IdeaPojo ideaPojo) {
        IdeaPo po = mapper.map(ideaPojo, IdeaPo.class);
        repository.saveAndFlush(po);
        return mapper.map(po, IdeaPojo.class);
    }

    @Override
    public void delete(int ideaId) {
        repository.delete(ideaId);
    }
}
